package com.lovegu.netty.server;

import com.lovegu.netty.res.RpcRequest;
import com.lovegu.netty.res.RpcResponse;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 老顾 1437594522@qq.com
 * @description
 * @date 2022/11/22 21:47
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final AtomicInteger atomicInteger = new AtomicInteger(1);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            //接收请求
            RpcRequest rpcRequest = (RpcRequest) msg;
            //服务端日志
            System.out.println("服务请求："+rpcRequest+"时间："+atomicInteger.getAndIncrement());
            //服务端消息
            RpcResponse messageFromServer = RpcResponse.builder().message("服务消息").build();
            //把消息内容写入并刷新
            ChannelFuture f = ctx.writeAndFlush(messageFromServer);
            //关闭监听器
            f.addListener(ChannelFutureListener.CLOSE);
        }finally {
            //释放消息
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        System.out.println("服务端捕捉异常："+cause);
        ctx.close();
    }
}
